package domain

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
	"listenboos-common/db"
	"listenboos-common/tools"
	"time"
	"ucenter/dao"
	"ucenter/internal/database"
	"ucenter/model"
	"ucenter/repo"
)

type CollectDomain struct {
	collectRepo repo.CollectRepo
}

func NewCollectDomain(mongoClient *database.MongoClient, db *db.ListenDB) *CollectDomain {
	return &CollectDomain{
		collectRepo: dao.NewCollectDao(mongoClient.Db, db),
	}
}
func (c *CollectDomain) Create(ctx context.Context, userId int64, trackId int64) (int64, error) {
	pro := model.Collect{
		UserId:     userId,
		TrackId:    trackId,
		CreateTime: time.Now().Unix(),
		UpdateTime: time.Now().Unix(),
		IsDeleted:  1,
	}
	isDeleted, err := c.collectRepo.Create(ctx, &pro)
	if err != nil {
		logx.Errorf("mongo 创建失败error: %v", err)
		return isDeleted, err
	}
	return isDeleted, nil
}
func (c *CollectDomain) Update(ctx context.Context, userId, trackId int64) (int64, error) {
	isDeleted, err := c.collectRepo.Update(ctx, userId, trackId)
	if err != nil {
		logx.Errorf("mongodb 内部更新错误 error: %v", err)
		return isDeleted, err
	}
	return isDeleted, nil
}
func (c *CollectDomain) UpdateMysql(ctx context.Context, userId, trackId int64) (int64, error) {
	isDeleted, err := c.collectRepo.UpdateMysql(ctx, userId, trackId)
	if err != nil {
		logx.Error(err)
		return isDeleted, errors.New("create collect error")
	}
	return isDeleted, nil
}
func (c *CollectDomain) CreateMysql(ctx context.Context, userId, trackId int64) (int64, error) {
	var col model.UserCollect
	now := tools.ToTimeString(time.Now().UnixMilli())
	col.UserId = userId
	col.TrackId = trackId
	col.CreateTime = now
	col.UpdateTime = now
	col.IsDeleted = 1
	isDeleted, err := c.collectRepo.CreateMysql(ctx, &col)
	if err != nil {
		logx.Error(err)
		return isDeleted, errors.New("create collect error")
	}
	return isDeleted, nil
}
func (c *CollectDomain) FindCollectTo1(ctx context.Context, userId int64, trackId int64) (*model.Collect, error) {
	collect, err := c.collectRepo.FindProcessTo1(ctx, userId, trackId)
	if err != nil {
		logx.Errorf("mongodb 内部查询错误 error: %v", err)
		return nil, nil
	}
	return collect, nil
}

func (c *CollectDomain) FindCollectMysql(ctx context.Context, userId int64, trackId int64) (int64, error) {
	isDeleted, err := c.collectRepo.FindCollectMysql(ctx, userId, trackId)
	if err != nil {
		logx.Error(err)
		return isDeleted, errors.New("create collect error")
	}
	return isDeleted, nil
}
